<!DOCTYPE html>
<html lang="en">
<head>
    
    <meta charset="utf-8">
    <title>data/TrialHandler.js - PsychoJS API</title>
    
    
    
        <meta name="keywords" content="psychopy, psychojs, api" />
        <meta name="keyword" content="psychopy, psychojs, api" />
    
    
    
    <script src="scripts/prettify/prettify.js"></script>
    <script src="scripts/prettify/lang-css.js"></script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
    <script src="scripts/nav.js" defer></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
  <div class="navicon"></div>
</label>

<label for="nav-trigger" class="overlay"></label>

<nav >
    
    <input type="text" id="nav-search" placeholder="Search" />
    
    <h2><a href="index.html">Home</a></h2><h2><a href="https://psychopy.org" target="_blank" class="menu-item" id="website_link" >Project Website</a></h2><h2><a href="https://discourse.psychopy.org/" target="_blank" class="menu-item" id="forum_link" >Forum</a></h2><h2><a href="https://github.com/psychopy/psychojs" target="_blank" class="menu-item" id="github_link" >Github</a></h2><h3>Modules</h3><ul><li><a href="module-core.html">core</a></li><li><a href="module-data.html">data</a></li><li><a href="module-sound.html">sound</a></li><li><a href="module-util.html">util</a><ul class='methods'><li data-type='method'><a href="module-util.html#~_match">_match</a></li></ul></li><li></li><li><a href="module-visual.html">visual</a></li></ul><h3>Classes</h3><ul><li><a href="AudioClip.html">AudioClip</a><ul class='methods'><li data-type='method'><a href="AudioClip.html#_base64ArrayBuffer">_base64ArrayBuffer</a></li><li data-type='method'><a href="AudioClip.html#_decodeAudio">_decodeAudio</a></li><li data-type='method'><a href="AudioClip.html#_GoogleTranscribe">_GoogleTranscribe</a></li><li data-type='method'><a href="AudioClip.html#download">download</a></li><li data-type='method'><a href="AudioClip.html#getDuration">getDuration</a></li><li data-type='method'><a href="AudioClip.html#setVolume">setVolume</a></li><li data-type='method'><a href="AudioClip.html#startPlayback">startPlayback</a></li><li data-type='method'><a href="AudioClip.html#stopPlayback">stopPlayback</a></li><li data-type='method'><a href="AudioClip.html#transcribe">transcribe</a></li><li data-type='method'><a href="AudioClip.html#upload">upload</a></li></ul></li><li><a href="AudioClipPlayer.html">AudioClipPlayer</a><ul class='methods'><li data-type='method'><a href="AudioClipPlayer.html#getDuration">getDuration</a></li><li data-type='method'><a href="AudioClipPlayer.html#play">play</a></li><li data-type='method'><a href="AudioClipPlayer.html#setDuration">setDuration</a></li><li data-type='method'><a href="AudioClipPlayer.html#setLoops">setLoops</a></li><li data-type='method'><a href="AudioClipPlayer.html#setVolume">setVolume</a></li><li data-type='method'><a href="AudioClipPlayer.html#stop">stop</a></li></ul></li><li><a href="BuilderKeyResponse.html">BuilderKeyResponse</a></li><li><a href="ButtonStim.html">ButtonStim</a><ul class='methods'><li data-type='method'><a href="ButtonStim.html#_addEventListeners">_addEventListeners</a></li><li data-type='method'><a href="ButtonStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="ButtonStim.html#_getAnchor">_getAnchor</a></li><li data-type='method'><a href="ButtonStim.html#_getDefaultLetterHeight">_getDefaultLetterHeight</a></li><li data-type='method'><a href="ButtonStim.html#_getTextInputOptions">_getTextInputOptions</a></li><li data-type='method'><a href="ButtonStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="ButtonStim.html#clear">clear</a></li><li data-type='method'><a href="ButtonStim.html#getText">getText</a></li><li data-type='method'><a href="ButtonStim.html#reset">reset</a></li><li data-type='method'><a href="ButtonStim.html#setAlignment">setAlignment</a></li><li data-type='method'><a href="ButtonStim.html#setAnchor">setAnchor</a></li><li data-type='method'><a href="ButtonStim.html#setBorderColor">setBorderColor</a></li><li data-type='method'><a href="ButtonStim.html#setColor">setColor</a></li><li data-type='method'><a href="ButtonStim.html#setFillColor">setFillColor</a></li><li data-type='method'><a href="ButtonStim.html#setFitToContent">setFitToContent</a></li><li data-type='method'><a href="ButtonStim.html#setFont">setFont</a></li><li data-type='method'><a href="ButtonStim.html#setLanguageStyle">setLanguageStyle</a></li><li data-type='method'><a href="ButtonStim.html#setLetterHeight">setLetterHeight</a></li><li data-type='method'><a href="ButtonStim.html#setSize">setSize</a></li><li data-type='method'><a href="ButtonStim.html#setText">setText</a></li></ul></li><li><a href="Clock.html">Clock</a><ul class='methods'><li data-type='method'><a href="Clock.html#add">add</a></li><li data-type='method'><a href="Clock.html#getLastResetTime">getLastResetTime</a></li><li data-type='method'><a href="Clock.html#getTime">getTime</a></li><li data-type='method'><a href="Clock.html#reset">reset</a></li></ul></li><li><a href="Color.html">Color</a><ul class='methods'><li data-type='method'><a href="Color.html#toString">toString</a></li></ul></li><li><a href="CountdownTimer.html">CountdownTimer</a><ul class='methods'><li data-type='method'><a href="CountdownTimer.html#add">add</a></li><li data-type='method'><a href="CountdownTimer.html#getLastResetTime">getLastResetTime</a></li><li data-type='method'><a href="CountdownTimer.html#getTime">getTime</a></li><li data-type='method'><a href="CountdownTimer.html#reset">reset</a></li></ul></li><li><a href="EventEmitter.html">EventEmitter</a><ul class='methods'><li data-type='method'><a href="EventEmitter.html#emit">emit</a></li><li data-type='method'><a href="EventEmitter.html#off">off</a></li><li data-type='method'><a href="EventEmitter.html#on">on</a></li><li data-type='method'><a href="EventEmitter.html#once">once</a></li></ul></li><li><a href="EventManager.html">EventManager</a><ul class='methods'><li data-type='method'><a href="EventManager.html#_addKeyListeners">_addKeyListeners</a></li><li data-type='method'><a href="EventManager.html#addMouseListeners">addMouseListeners</a></li><li data-type='method'><a href="EventManager.html#clearEvents">clearEvents</a></li><li data-type='method'><a href="EventManager.html#clearKeys">clearKeys</a></li><li data-type='method'><a href="EventManager.html#getKeys">getKeys</a></li><li data-type='method'><a href="EventManager.html#getMouseInfo">getMouseInfo</a></li><li data-type='method'><a href="EventManager.html#resetMoveClock">resetMoveClock</a></li><li data-type='method'><a href="EventManager.html#startMoveClock">startMoveClock</a></li><li data-type='method'><a href="EventManager.html#stopMoveClock">stopMoveClock</a></li></ul></li><li><a href="ExperimentHandler.html">ExperimentHandler</a><ul class='methods'><li data-type='method'><a href="ExperimentHandler.html#addData">addData</a></li><li data-type='method'><a href="ExperimentHandler.html#addLoop">addLoop</a></li><li data-type='method'><a href="ExperimentHandler.html#isEntryEmpty">isEntryEmpty</a></li><li data-type='method'><a href="ExperimentHandler.html#nextEntry">nextEntry</a></li><li data-type='method'><a href="ExperimentHandler.html#removeLoop">removeLoop</a></li><li data-type='method'><a href="ExperimentHandler.html#save">save</a></li></ul></li><li><a href="FaceDetector.html">FaceDetector</a><ul class='methods'><li data-type='method'><a href="FaceDetector.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="FaceDetector.html#_initFaceApi">_initFaceApi</a></li><li data-type='method'><a href="FaceDetector.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="FaceDetector.html#isReady">isReady</a></li><li data-type='method'><a href="FaceDetector.html#setInput">setInput</a></li><li data-type='method'><a href="FaceDetector.html#start">start</a></li><li data-type='method'><a href="FaceDetector.html#stop">stop</a></li></ul></li><li><a href="Form.html">Form</a><ul class='methods'><li data-type='method'><a href="Form.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="Form.html#_getBoundingBox_px">_getBoundingBox_px</a></li><li data-type='method'><a href="Form.html#_importItems">_importItems</a></li><li data-type='method'><a href="Form.html#_onChange">_onChange</a></li><li data-type='method'><a href="Form.html#_processItems">_processItems</a></li><li data-type='method'><a href="Form.html#_sanitizeItems">_sanitizeItems</a></li><li data-type='method'><a href="Form.html#_setupStimuli">_setupStimuli</a></li><li data-type='method'><a href="Form.html#_updateDecorations">_updateDecorations</a></li><li data-type='method'><a href="Form.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Form.html#_updateVisibleStimuli">_updateVisibleStimuli</a></li><li data-type='method'><a href="Form.html#addDataToExp">addDataToExp</a></li><li data-type='method'><a href="Form.html#contains">contains</a></li><li data-type='method'><a href="Form.html#draw">draw</a></li><li data-type='method'><a href="Form.html#formComplete">formComplete</a></li><li data-type='method'><a href="Form.html#getData">getData</a></li><li data-type='method'><a href="Form.html#hide">hide</a></li><li data-type='method'><a href="Form.html#refresh">refresh</a></li><li data-type='method'><a href="Form.html#release">release</a></li><li data-type='method'><a href="Form.html#reset">reset</a></li><li data-type='method'><a href="Form.html#setAutoDraw">setAutoDraw</a></li><li data-type='method'><a href="Form.html#setDepth">setDepth</a></li><li data-type='method'><a href="Form.html#setOri">setOri</a></li><li data-type='method'><a href="Form.html#setPos">setPos</a></li><li data-type='method'><a href="Form.html#setSize">setSize</a></li></ul></li><li><a href="GratingStim.html">GratingStim</a><ul class='methods'><li data-type='method'><a href="GratingStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="GratingStim.html#_getDisplaySize">_getDisplaySize</a></li><li data-type='method'><a href="GratingStim.html#_getPixiMeshFromPredefinedShaders">_getPixiMeshFromPredefinedShaders</a></li><li data-type='method'><a href="GratingStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="GratingStim.html#setBlendmode">setBlendmode</a></li><li data-type='method'><a href="GratingStim.html#setColor">setColor</a></li><li data-type='method'><a href="GratingStim.html#setColorSpace">setColorSpace</a></li><li data-type='method'><a href="GratingStim.html#setInterpolate">setInterpolate</a></li><li data-type='method'><a href="GratingStim.html#setMask">setMask</a></li><li data-type='method'><a href="GratingStim.html#setOpacity">setOpacity</a></li><li data-type='method'><a href="GratingStim.html#setPhase">setPhase</a></li><li data-type='method'><a href="GratingStim.html#setSF">setSF</a></li><li data-type='method'><a href="GratingStim.html#setTex">setTex</a></li></ul></li><li><a href="GUI.html">GUI</a><ul class='methods'><li data-type='method'><a href="GUI.html#_onCancelExperiment">_onCancelExperiment</a></li><li data-type='method'><a href="GUI.html#_onResourceEvents">_onResourceEvents</a></li><li data-type='method'><a href="GUI.html#_onStartExperiment">_onStartExperiment</a></li><li data-type='method'><a href="GUI.html#_setProgressMessage">_setProgressMessage</a></li><li data-type='method'><a href="GUI.html#_updateDialog">_updateDialog</a></li><li data-type='method'><a href="GUI.html#_updateProgressBar">_updateProgressBar</a></li><li data-type='method'><a href="GUI.html#_userFriendlyError">_userFriendlyError</a></li><li data-type='method'><a href="GUI.html#closeDialog">closeDialog</a></li><li data-type='method'><a href="GUI.html#dialog">dialog</a></li><li data-type='method'><a href="GUI.html#DlgFromDict">DlgFromDict</a></li><li data-type='method'><a href="GUI.html#finishDialog">finishDialog</a></li></ul></li><li><a href="ImageStim.html">ImageStim</a><ul class='methods'><li data-type='method'><a href="ImageStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="ImageStim.html#_getDisplaySize">_getDisplaySize</a></li><li data-type='method'><a href="ImageStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="ImageStim.html#setImage">setImage</a></li><li data-type='method'><a href="ImageStim.html#setInterpolate">setInterpolate</a></li><li data-type='method'><a href="ImageStim.html#setMask">setMask</a></li></ul></li><li><a href="Keyboard.html">Keyboard</a><ul class='methods'><li data-type='method'><a href="Keyboard.html#_addKeyListeners">_addKeyListeners</a></li><li data-type='method'><a href="Keyboard.html#clearEvents">clearEvents</a></li><li data-type='method'><a href="Keyboard.html#getEvents">getEvents</a></li><li data-type='method'><a href="Keyboard.html#getKeys">getKeys</a></li><li data-type='method'><a href="Keyboard.html#start">start</a></li><li data-type='method'><a href="Keyboard.html#stop">stop</a></li></ul></li><li><a href="KeyPress.html">KeyPress</a></li><li><a href="Logger.html">Logger</a><ul class='methods'><li data-type='method'><a href="Logger.html#_customConsoleLayout">_customConsoleLayout</a></li><li data-type='method'><a href="Logger.html#_getValue">_getValue</a></li><li data-type='method'><a href="Logger.html#_throttle">_throttle</a></li><li data-type='method'><a href="Logger.html#data">data</a></li><li data-type='method'><a href="Logger.html#exp">exp</a></li><li data-type='method'><a href="Logger.html#flush">flush</a></li><li data-type='method'><a href="Logger.html#log">log</a></li><li data-type='method'><a href="Logger.html#setLevel">setLevel</a></li></ul></li><li><a href="Microphone.html">Microphone</a><ul class='methods'><li data-type='method'><a href="Microphone.html#_onChange">_onChange</a></li><li data-type='method'><a href="Microphone.html#_prepareRecording">_prepareRecording</a></li><li data-type='method'><a href="Microphone.html#download">download</a></li><li data-type='method'><a href="Microphone.html#flush">flush</a></li><li data-type='method'><a href="Microphone.html#getRecording">getRecording</a></li><li data-type='method'><a href="Microphone.html#pause">pause</a></li><li data-type='method'><a href="Microphone.html#resume">resume</a></li><li data-type='method'><a href="Microphone.html#start">start</a></li><li data-type='method'><a href="Microphone.html#stop">stop</a></li><li data-type='method'><a href="Microphone.html#upload">upload</a></li></ul></li><li><a href="MinimalStim.html">MinimalStim</a><ul class='methods'><li data-type='method'><a href="MinimalStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="MinimalStim.html#contains">contains</a></li><li data-type='method'><a href="MinimalStim.html#draw">draw</a></li><li data-type='method'><a href="MinimalStim.html#hide">hide</a></li><li data-type='method'><a href="MinimalStim.html#release">release</a></li><li data-type='method'><a href="MinimalStim.html#setAutoDraw">setAutoDraw</a></li></ul></li><li><a href="module-core.PsychoJS.html">PsychoJS</a><ul class='methods'><li data-type='method'><a href="module-core.PsychoJS.html#_captureErrors">_captureErrors</a></li><li data-type='method'><a href="module-core.PsychoJS.html#_configure">_configure</a></li><li data-type='method'><a href="module-core.PsychoJS.html#_getParticipantIPInfo">_getParticipantIPInfo</a></li><li data-type='method'><a href="module-core.PsychoJS.html#_makeStatusTopLevel">_makeStatusTopLevel</a></li><li data-type='method'><a href="module-core.PsychoJS.html#getEnvironment">getEnvironment</a></li><li data-type='method'><a href="module-core.PsychoJS.html#importAttributes">importAttributes</a></li><li data-type='method'><a href="module-core.PsychoJS.html#openWindow">openWindow</a></li><li data-type='method'><a href="module-core.PsychoJS.html#quit">quit</a></li><li data-type='method'><a href="module-core.PsychoJS.html#schedule">schedule</a></li><li data-type='method'><a href="module-core.PsychoJS.html#scheduleCondition">scheduleCondition</a></li><li data-type='method'><a href="module-core.PsychoJS.html#setRedirectUrls">setRedirectUrls</a></li><li data-type='method'><a href="module-core.PsychoJS.html#start">start</a></li><li data-type='method'><a href="module-core.PsychoJS.html#waitForResources">waitForResources</a></li></ul></li><li><a href="module-data.TrialHandler.html">TrialHandler</a><ul class='methods'><li data-type='method'><a href="module-data.TrialHandler.html#_prepareSequence">_prepareSequence</a></li><li data-type='method'><a href="module-data.TrialHandler.html#_prepareTrialList">_prepareTrialList</a></li><li data-type='method'><a href="module-data.TrialHandler.html#addData">addData</a></li><li data-type='method'><a href="module-data.TrialHandler.html#forEach">forEach</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getAttributes">getAttributes</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getCurrentTrial">getCurrentTrial</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getEarlierTrial">getEarlierTrial</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getFutureTrial">getFutureTrial</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getSnapshot">getSnapshot</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getTrial">getTrial</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getTrialIndex">getTrialIndex</a></li><li data-type='method'><a href="module-data.TrialHandler.html#next">next</a></li><li data-type='method'><a href="module-data.TrialHandler.html#setSeed">setSeed</a></li><li data-type='method'><a href="module-data.TrialHandler.html#setTrialIndex">setTrialIndex</a></li><li data-type='method'><a href="module-data.TrialHandler.html#Symbol.iterator">Symbol.iterator</a></li></ul></li><li><a href="module-hardware.Camera.html">Camera</a><ul class='methods'><li data-type='method'><a href="module-hardware.Camera.html#_onChange">_onChange</a></li><li data-type='method'><a href="module-hardware.Camera.html#_prepareRecording">_prepareRecording</a></li><li data-type='method'><a href="module-hardware.Camera.html#_upload">_upload</a></li><li data-type='method'><a href="module-hardware.Camera.html#authorize">authorize</a></li><li data-type='method'><a href="module-hardware.Camera.html#close">close</a></li><li data-type='method'><a href="module-hardware.Camera.html#flush">flush</a></li><li data-type='method'><a href="module-hardware.Camera.html#getRecording">getRecording</a></li><li data-type='method'><a href="module-hardware.Camera.html#getStream">getStream</a></li><li data-type='method'><a href="module-hardware.Camera.html#getVideo">getVideo</a></li><li data-type='method'><a href="module-hardware.Camera.html#isReady">isReady</a></li><li data-type='method'><a href="module-hardware.Camera.html#open">open</a></li><li data-type='method'><a href="module-hardware.Camera.html#pause">pause</a></li><li data-type='method'><a href="module-hardware.Camera.html#record">record</a></li><li data-type='method'><a href="module-hardware.Camera.html#resume">resume</a></li><li data-type='method'><a href="module-hardware.Camera.html#stop">stop</a></li></ul></li><li><a href="module-sound.Sound.html">Sound</a><ul class='methods'><li data-type='method'><a href="module-sound.Sound.html#_getPlayer">_getPlayer</a></li><li data-type='method'><a href="module-sound.Sound.html#getDuration">getDuration</a></li><li data-type='method'><a href="module-sound.Sound.html#play">play</a></li><li data-type='method'><a href="module-sound.Sound.html#setLoops">setLoops</a></li><li data-type='method'><a href="module-sound.Sound.html#setSecs">setSecs</a></li><li data-type='method'><a href="module-sound.Sound.html#setSound">setSound</a></li><li data-type='method'><a href="module-sound.Sound.html#setVolume">setVolume</a></li><li data-type='method'><a href="module-sound.Sound.html#stop">stop</a></li></ul></li><li><a href="module-util.PsychObject.html">PsychObject</a><ul class='methods'><li data-type='method'><a href="module-util.PsychObject.html#_addAttribute">_addAttribute</a></li><li data-type='method'><a href="module-util.PsychObject.html#_setAttribute">_setAttribute</a></li><li data-type='method'><a href="module-util.PsychObject.html#emit">emit</a></li><li data-type='method'><a href="module-util.PsychObject.html#off">off</a></li><li data-type='method'><a href="module-util.PsychObject.html#on">on</a></li><li data-type='method'><a href="module-util.PsychObject.html#once">once</a></li><li data-type='method'><a href="module-util.PsychObject.html#toString">toString</a></li></ul></li><li><a href="module-visual.VisualStim.html">VisualStim</a><ul class='methods'><li data-type='method'><a href="module-visual.VisualStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="module-visual.VisualStim.html#_getBoundingBox_px">_getBoundingBox_px</a></li><li data-type='method'><a href="module-visual.VisualStim.html#_onChange">_onChange</a></li><li data-type='method'><a href="module-visual.VisualStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="module-visual.VisualStim.html#contains">contains</a></li><li data-type='method'><a href="module-visual.VisualStim.html#draw">draw</a></li><li data-type='method'><a href="module-visual.VisualStim.html#hide">hide</a></li><li data-type='method'><a href="module-visual.VisualStim.html#refresh">refresh</a></li><li data-type='method'><a href="module-visual.VisualStim.html#release">release</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setAutoDraw">setAutoDraw</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setDepth">setDepth</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setOri">setOri</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setPos">setPos</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setSize">setSize</a></li></ul></li><li><a href="MonotonicClock.html">MonotonicClock</a><ul class='methods'><li data-type='method'><a href="MonotonicClock.html#getLastResetTime">getLastResetTime</a></li><li data-type='method'><a href="MonotonicClock.html#getTime">getTime</a></li></ul></li><li><a href="Mouse.html">Mouse</a><ul class='methods'><li data-type='method'><a href="Mouse.html#clickReset">clickReset</a></li><li data-type='method'><a href="Mouse.html#getPos">getPos</a></li><li data-type='method'><a href="Mouse.html#getPressed">getPressed</a></li><li data-type='method'><a href="Mouse.html#getRel">getRel</a></li><li data-type='method'><a href="Mouse.html#getWheelRel">getWheelRel</a></li><li data-type='method'><a href="Mouse.html#isPressedIn">isPressedIn</a></li><li data-type='method'><a href="Mouse.html#mouseMoved">mouseMoved</a></li><li data-type='method'><a href="Mouse.html#mouseMoveTime">mouseMoveTime</a></li></ul></li><li><a href="MovieStim.html">MovieStim</a><ul class='methods'><li data-type='method'><a href="MovieStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="MovieStim.html#_getDisplaySize">_getDisplaySize</a></li><li data-type='method'><a href="MovieStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="MovieStim.html#pause">pause</a></li><li data-type='method'><a href="MovieStim.html#play">play</a></li><li data-type='method'><a href="MovieStim.html#reset">reset</a></li><li data-type='method'><a href="MovieStim.html#seek">seek</a></li><li data-type='method'><a href="MovieStim.html#setMovie">setMovie</a></li><li data-type='method'><a href="MovieStim.html#stop">stop</a></li></ul></li><li><a href="MultiStairHandler.html">MultiStairHandler</a><ul class='methods'><li data-type='method'><a href="MultiStairHandler.html#_nextTrial">_nextTrial</a></li><li data-type='method'><a href="MultiStairHandler.html#_prepareStaircases">_prepareStaircases</a></li><li data-type='method'><a href="MultiStairHandler.html#_validateConditions">_validateConditions</a></li><li data-type='method'><a href="MultiStairHandler.html#addResponse">addResponse</a></li></ul></li><li><a href="Polygon.html">Polygon</a><ul class='methods'><li data-type='method'><a href="Polygon.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="Polygon.html#_getPixiPolygon">_getPixiPolygon</a></li><li data-type='method'><a href="Polygon.html#_getVertices_px">_getVertices_px</a></li><li data-type='method'><a href="Polygon.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Polygon.html#contains">contains</a></li><li data-type='method'><a href="Polygon.html#setEdges">setEdges</a></li><li data-type='method'><a href="Polygon.html#setRadius">setRadius</a></li><li data-type='method'><a href="Polygon.html#setVertices">setVertices</a></li></ul></li><li><a href="QuestHandler.html">QuestHandler</a><ul class='methods'><li data-type='method'><a href="QuestHandler.html#_estimateQuestValue">_estimateQuestValue</a></li><li data-type='method'><a href="QuestHandler.html#_setupJsQuest">_setupJsQuest</a></li><li data-type='method'><a href="QuestHandler.html#addResponse">addResponse</a></li><li data-type='method'><a href="QuestHandler.html#confInterval">confInterval</a></li><li data-type='method'><a href="QuestHandler.html#getQuestValue">getQuestValue</a></li><li data-type='method'><a href="QuestHandler.html#mean">mean</a></li><li data-type='method'><a href="QuestHandler.html#mode">mode</a></li><li data-type='method'><a href="QuestHandler.html#quantile">quantile</a></li><li data-type='method'><a href="QuestHandler.html#sd">sd</a></li><li data-type='method'><a href="QuestHandler.html#setMethod">setMethod</a></li><li data-type='method'><a href="QuestHandler.html#simulate">simulate</a></li></ul></li><li><a href="Rect.html">Rect</a><ul class='methods'><li data-type='method'><a href="Rect.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="Rect.html#_getPixiPolygon">_getPixiPolygon</a></li><li data-type='method'><a href="Rect.html#_getVertices_px">_getVertices_px</a></li><li data-type='method'><a href="Rect.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Rect.html#_updateVertices">_updateVertices</a></li><li data-type='method'><a href="Rect.html#contains">contains</a></li><li data-type='method'><a href="Rect.html#setHeight">setHeight</a></li><li data-type='method'><a href="Rect.html#setVertices">setVertices</a></li><li data-type='method'><a href="Rect.html#setWidth">setWidth</a></li></ul></li><li><a href="Scheduler.html">Scheduler</a><ul class='methods'><li data-type='method'><a href="Scheduler.html#add">add</a></li><li data-type='method'><a href="Scheduler.html#addConditional">addConditional</a></li><li data-type='method'><a href="Scheduler.html#start">start</a></li><li data-type='method'><a href="Scheduler.html#stop">stop</a></li></ul></li><li><a href="ServerManager.html">ServerManager</a><ul class='methods'><li data-type='method'><a href="ServerManager.html#_downloadResources">_downloadResources</a></li><li data-type='method'><a href="ServerManager.html#_listResources">_listResources</a></li><li data-type='method'><a href="ServerManager.html#_queryServerAPI">_queryServerAPI</a></li><li data-type='method'><a href="ServerManager.html#_setupPreloadQueue">_setupPreloadQueue</a></li><li data-type='method'><a href="ServerManager.html#closeSession">closeSession</a></li><li data-type='method'><a href="ServerManager.html#getConfiguration">getConfiguration</a></li><li data-type='method'><a href="ServerManager.html#getResource">getResource</a></li><li data-type='method'><a href="ServerManager.html#getResourceStatus">getResourceStatus</a></li><li data-type='method'><a href="ServerManager.html#openSession">openSession</a></li><li data-type='method'><a href="ServerManager.html#prepareResources">prepareResources</a></li><li data-type='method'><a href="ServerManager.html#resetStatus">resetStatus</a></li><li data-type='method'><a href="ServerManager.html#setStatus">setStatus</a></li><li data-type='method'><a href="ServerManager.html#uploadAudioVideo">uploadAudioVideo</a></li><li data-type='method'><a href="ServerManager.html#uploadData">uploadData</a></li><li data-type='method'><a href="ServerManager.html#uploadLog">uploadLog</a></li><li data-type='method'><a href="ServerManager.html#waitForResources">waitForResources</a></li></ul></li><li><a href="ShapeStim.html">ShapeStim</a><ul class='methods'><li data-type='method'><a href="ShapeStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="ShapeStim.html#_getPixiPolygon">_getPixiPolygon</a></li><li data-type='method'><a href="ShapeStim.html#_getVertices_px">_getVertices_px</a></li><li data-type='method'><a href="ShapeStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="ShapeStim.html#contains">contains</a></li><li data-type='method'><a href="ShapeStim.html#setVertices">setVertices</a></li></ul></li><li><a href="Shelf.html">Shelf</a><ul class='methods'><li data-type='method'><a href="Shelf.html#_checkAvailability">_checkAvailability</a></li><li data-type='method'><a href="Shelf.html#_checkKey">_checkKey</a></li><li data-type='method'><a href="Shelf.html#_getValue">_getValue</a></li><li data-type='method'><a href="Shelf.html#_updateValue">_updateValue</a></li><li data-type='method'><a href="Shelf.html#addIntegerValue">addIntegerValue</a></li><li data-type='method'><a href="Shelf.html#appendListValue">appendListValue</a></li><li data-type='method'><a href="Shelf.html#clearListValue">clearListValue</a></li><li data-type='method'><a href="Shelf.html#counterBalanceSelect">counterBalanceSelect</a></li><li data-type='method'><a href="Shelf.html#flipBooleanValue">flipBooleanValue</a></li><li data-type='method'><a href="Shelf.html#getBooleanValue">getBooleanValue</a></li><li data-type='method'><a href="Shelf.html#getDictionaryFieldNames">getDictionaryFieldNames</a></li><li data-type='method'><a href="Shelf.html#getDictionaryFieldValue">getDictionaryFieldValue</a></li><li data-type='method'><a href="Shelf.html#getDictionaryValue">getDictionaryValue</a></li><li data-type='method'><a href="Shelf.html#getIntegerValue">getIntegerValue</a></li><li data-type='method'><a href="Shelf.html#getListValue">getListValue</a></li><li data-type='method'><a href="Shelf.html#getTextValue">getTextValue</a></li><li data-type='method'><a href="Shelf.html#incrementComponent">incrementComponent</a></li><li data-type='method'><a href="Shelf.html#popListValue">popListValue</a></li><li data-type='method'><a href="Shelf.html#setBooleanValue">setBooleanValue</a></li><li data-type='method'><a href="Shelf.html#setDictionaryFieldValue">setDictionaryFieldValue</a></li><li data-type='method'><a href="Shelf.html#setDictionaryValue">setDictionaryValue</a></li><li data-type='method'><a href="Shelf.html#setIntegerValue">setIntegerValue</a></li><li data-type='method'><a href="Shelf.html#setListValue">setListValue</a></li><li data-type='method'><a href="Shelf.html#setTextValue">setTextValue</a></li><li data-type='method'><a href="Shelf.html#shuffleListValue">shuffleListValue</a></li></ul></li><li><a href="Slider.html">Slider</a><ul class='methods'><li data-type='method'><a href="Slider.html#_addEventListeners">_addEventListeners</a></li><li data-type='method'><a href="Slider.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="Slider.html#_getBoundingBox_px">_getBoundingBox_px</a></li><li data-type='method'><a href="Slider.html#_getPosition_px">_getPosition_px</a></li><li data-type='method'><a href="Slider.html#_getTextStyle">_getTextStyle</a></li><li data-type='method'><a href="Slider.html#_granularise">_granularise</a></li><li data-type='method'><a href="Slider.html#_handlePointerDown">_handlePointerDown</a></li><li data-type='method'><a href="Slider.html#_handlePointerMove">_handlePointerMove</a></li><li data-type='method'><a href="Slider.html#_handlePointerUp">_handlePointerUp</a></li><li data-type='method'><a href="Slider.html#_isHorizontal">_isHorizontal</a></li><li data-type='method'><a href="Slider.html#_onChange">_onChange</a></li><li data-type='method'><a href="Slider.html#_posToRating">_posToRating</a></li><li data-type='method'><a href="Slider.html#_ratingToPos">_ratingToPos</a></li><li data-type='method'><a href="Slider.html#_removeEventListeners">_removeEventListeners</a></li><li data-type='method'><a href="Slider.html#_sanitizeAttributes">_sanitizeAttributes</a></li><li data-type='method'><a href="Slider.html#_setupBar">_setupBar</a></li><li data-type='method'><a href="Slider.html#_setupLabels">_setupLabels</a></li><li data-type='method'><a href="Slider.html#_setupMarker">_setupMarker</a></li><li data-type='method'><a href="Slider.html#_setupSlider">_setupSlider</a></li><li data-type='method'><a href="Slider.html#_setupStyle">_setupStyle</a></li><li data-type='method'><a href="Slider.html#_setupTicks">_setupTicks</a></li><li data-type='method'><a href="Slider.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Slider.html#contains">contains</a></li><li data-type='method'><a href="Slider.html#draw">draw</a></li><li data-type='method'><a href="Slider.html#getRating">getRating</a></li><li data-type='method'><a href="Slider.html#getRT">getRT</a></li><li data-type='method'><a href="Slider.html#hide">hide</a></li><li data-type='method'><a href="Slider.html#isMarkerDragging">isMarkerDragging</a></li><li data-type='method'><a href="Slider.html#recordRating">recordRating</a></li><li data-type='method'><a href="Slider.html#refresh">refresh</a></li><li data-type='method'><a href="Slider.html#release">release</a></li><li data-type='method'><a href="Slider.html#reset">reset</a></li><li data-type='method'><a href="Slider.html#setAutoDraw">setAutoDraw</a></li><li data-type='method'><a href="Slider.html#setDepth">setDepth</a></li><li data-type='method'><a href="Slider.html#setMarkerPos">setMarkerPos</a></li><li data-type='method'><a href="Slider.html#setOri">setOri</a></li><li data-type='method'><a href="Slider.html#setPos">setPos</a></li><li data-type='method'><a href="Slider.html#setRating">setRating</a></li><li data-type='method'><a href="Slider.html#setReadOnly">setReadOnly</a></li><li data-type='method'><a href="Slider.html#setSize">setSize</a></li></ul></li><li><a href="SpeechRecognition.html">SpeechRecognition</a><ul class='methods'><li data-type='method'><a href="SpeechRecognition.html#_onChange">_onChange</a></li><li data-type='method'><a href="SpeechRecognition.html#_prepareRecognition">_prepareRecognition</a></li><li data-type='method'><a href="SpeechRecognition.html#clearTranscripts">clearTranscripts</a></li><li data-type='method'><a href="SpeechRecognition.html#getTranscripts">getTranscripts</a></li><li data-type='method'><a href="SpeechRecognition.html#start">start</a></li><li data-type='method'><a href="SpeechRecognition.html#stop">stop</a></li></ul></li><li><a href="TextBox.html">TextBox</a><ul class='methods'><li data-type='method'><a href="TextBox.html#_addEventListeners">_addEventListeners</a></li><li data-type='method'><a href="TextBox.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="TextBox.html#_getAnchor">_getAnchor</a></li><li data-type='method'><a href="TextBox.html#_getDefaultLetterHeight">_getDefaultLetterHeight</a></li><li data-type='method'><a href="TextBox.html#_getTextInputOptions">_getTextInputOptions</a></li><li data-type='method'><a href="TextBox.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="TextBox.html#clear">clear</a></li><li data-type='method'><a href="TextBox.html#getText">getText</a></li><li data-type='method'><a href="TextBox.html#reset">reset</a></li><li data-type='method'><a href="TextBox.html#setAlignment">setAlignment</a></li><li data-type='method'><a href="TextBox.html#setAnchor">setAnchor</a></li><li data-type='method'><a href="TextBox.html#setBorderColor">setBorderColor</a></li><li data-type='method'><a href="TextBox.html#setColor">setColor</a></li><li data-type='method'><a href="TextBox.html#setFillColor">setFillColor</a></li><li data-type='method'><a href="TextBox.html#setFitToContent">setFitToContent</a></li><li data-type='method'><a href="TextBox.html#setFont">setFont</a></li><li data-type='method'><a href="TextBox.html#setLanguageStyle">setLanguageStyle</a></li><li data-type='method'><a href="TextBox.html#setLetterHeight">setLetterHeight</a></li><li data-type='method'><a href="TextBox.html#setSize">setSize</a></li><li data-type='method'><a href="TextBox.html#setText">setText</a></li></ul></li><li><a href="TextStim.html">TextStim</a><ul class='methods'><li data-type='method'><a href="TextStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="TextStim.html#_getAnchor">_getAnchor</a></li><li data-type='method'><a href="TextStim.html#_getDefaultLetterHeight">_getDefaultLetterHeight</a></li><li data-type='method'><a href="TextStim.html#_getDefaultWrapWidth">_getDefaultWrapWidth</a></li><li data-type='method'><a href="TextStim.html#_getTextStyle">_getTextStyle</a></li><li data-type='method'><a href="TextStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="TextStim.html#getBoundingBox">getBoundingBox</a></li><li data-type='method'><a href="TextStim.html#getTextMetrics">getTextMetrics</a></li><li data-type='method'><a href="TextStim.html#setColor">setColor</a></li></ul></li><li><a href="TonePlayer.html">TonePlayer</a><ul class='methods'><li data-type='method'><a href="TonePlayer.html#_initSoundLibrary">_initSoundLibrary</a></li><li data-type='method'><a href="TonePlayer.html#getDuration">getDuration</a></li><li data-type='method'><a href="TonePlayer.html#play">play</a></li><li data-type='method'><a href="TonePlayer.html#setDuration">setDuration</a></li><li data-type='method'><a href="TonePlayer.html#setLoops">setLoops</a></li><li data-type='method'><a href="TonePlayer.html#setVolume">setVolume</a></li><li data-type='method'><a href="TonePlayer.html#stop">stop</a></li></ul></li><li><a href="TrackPlayer.html">TrackPlayer</a><ul class='methods'><li data-type='method'><a href="TrackPlayer.html#getDuration">getDuration</a></li><li data-type='method'><a href="TrackPlayer.html#play">play</a></li><li data-type='method'><a href="TrackPlayer.html#setDuration">setDuration</a></li><li data-type='method'><a href="TrackPlayer.html#setLoops">setLoops</a></li><li data-type='method'><a href="TrackPlayer.html#setVolume">setVolume</a></li><li data-type='method'><a href="TrackPlayer.html#stop">stop</a></li></ul></li><li><a href="Transcript.html">Transcript</a></li><li><a href="Window.html">Window</a><ul class='methods'><li data-type='method'><a href="Window.html#_fullRefresh">_fullRefresh</a></li><li data-type='method'><a href="Window.html#_refresh">_refresh</a></li><li data-type='method'><a href="Window.html#_setupPixi">_setupPixi</a></li><li data-type='method'><a href="Window.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Window.html#_writeLogOnFlip">_writeLogOnFlip</a></li><li data-type='method'><a href="Window.html#addPixiObject">addPixiObject</a></li><li data-type='method'><a href="Window.html#adjustScreenSize">adjustScreenSize</a></li><li data-type='method'><a href="Window.html#callOnFlip">callOnFlip</a></li><li data-type='method'><a href="Window.html#close">close</a></li><li data-type='method'><a href="Window.html#closeFullScreen">closeFullScreen</a></li><li data-type='method'><a href="Window.html#getActualFrameRate">getActualFrameRate</a></li><li data-type='method'><a href="Window.html#logOnFlip">logOnFlip</a></li><li data-type='method'><a href="Window.html#removePixiObject">removePixiObject</a></li><li data-type='method'><a href="Window.html#render">render</a></li></ul></li></ul><h3>Interfaces</h3><ul><li><a href="SoundPlayer.html">SoundPlayer</a><ul class='methods'><li data-type='method'><a href="SoundPlayer.html#getDuration">getDuration</a></li><li data-type='method'><a href="SoundPlayer.html#play">play</a></li><li data-type='method'><a href="SoundPlayer.html#setDuration">setDuration</a></li><li data-type='method'><a href="SoundPlayer.html#setLoops">setLoops</a></li><li data-type='method'><a href="SoundPlayer.html#setVolume">setVolume</a></li><li data-type='method'><a href="SoundPlayer.html#stop">stop</a></li></ul></li></ul><h3>Mixins</h3><ul><li><a href="module-core.WindowMixin.html">WindowMixin</a><ul class='methods'><li data-type='method'><a href="module-core.WindowMixin.html#_getHorLengthPix">_getHorLengthPix</a></li><li data-type='method'><a href="module-core.WindowMixin.html#_getLengthPix">_getLengthPix</a></li><li data-type='method'><a href="module-core.WindowMixin.html#_getLengthUnits">_getLengthUnits</a></li><li data-type='method'><a href="module-core.WindowMixin.html#_getVerLengthPix">_getVerLengthPix</a></li></ul></li><li><a href="module-util.ColorMixin.html">ColorMixin</a><ul class='methods'><li data-type='method'><a href="module-util.ColorMixin.html#getContrastedColor">getContrastedColor</a></li><li data-type='method'><a href="module-util.ColorMixin.html#setColor">setColor</a></li><li data-type='method'><a href="module-util.ColorMixin.html#setContrast">setContrast</a></li></ul></li></ul>
</nav>

<div id="main">
    
    <h1 class="page-title">data/TrialHandler.js</h1>
    

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>/** @module data */
/**
 * Trial Handler
 *
 * @author Alain Pitiot
 * @author Hiroyuki Sogo &amp; Sotiri Bakagiannis  - better support for BOM and accented characters
 * @version 2022.2.3
 * @copyright (c) 2017-2020 Ilixa Ltd. (http://ilixa.com) (c) 2020-2022 Open Science Tools Ltd. (https://opensciencetools.org)
 * @license Distributed under the terms of the MIT License
 */

import seedrandom from "seedrandom";
import * as XLSX from "xlsx";
import { PsychObject } from "../util/PsychObject.js";
import * as util from "../util/Util.js";

/**
 * &lt;p>A Trial Handler handles the importing and sequencing of conditions.&lt;/p>
 *
 * @extends PsychObject
 */
export class TrialHandler extends PsychObject
{
	/**
	 * Getter for experimentHandler.
	 */
	get experimentHandler()
	{
		return this._experimentHandler;
	}

	/**
	 * Setter for experimentHandler.
	 */
	set experimentHandler(exp)
	{
		this._experimentHandler = exp;
	}

	/**
	 * @param {Object} options - the handler options
	 * @param {module:core.PsychoJS} options.psychoJS - the PsychoJS instance
	 * @param {Array.&lt;Object> | String} [options.trialList= [undefined] ] - if it is a string, we treat it as the name of a condition resource
	 * @param {number} options.nReps - number of repetitions
	 * @param {module:data.TrialHandler.Method} options.method - the trial method
	 * @param {Object} options.extraInfo - additional information to be stored alongside the trial data, e.g. session ID, participant ID, etc.
	 * @param {number} options.seed - seed for the random number generator
	 * @param {boolean} [options.autoLog= false] - whether or not to log
	 *
	 * @todo extraInfo is not taken into account, we use the expInfo of the ExperimentHandler instead
	 */
	constructor({
		psychoJS,
		trialList = [undefined],
		nReps,
		method = TrialHandler.Method.RANDOM,
		extraInfo = [],
		seed,
		name,
		autoLog = true,
	} = {})
	{
		super(psychoJS);

		this._addAttribute("trialList", trialList);
		this._addAttribute("nReps", nReps);
		this._addAttribute("method", method);
		this._addAttribute("extraInfo", extraInfo);
		this._addAttribute("name", name);
		this._addAttribute("autoLog", autoLog);
		this._addAttribute("seed", seed);
		this._prepareTrialList();

		// number of stimuli
		this.nStim = this.trialList.length;

		// the total number of trials that will be run:
		this.nTotal = this.nReps * this.nStim;

		// the total number of trial remaining
		this.nRemaining = this.nTotal;

		// the current repeat:
		this.thisRepN = 0;

		// the current trial number within the current repeat:
		this.thisTrialN = -1;

		// total number of trials completed so far:
		this.thisN = -1;

		// the index of the current trial in the conditions list
		this.thisIndex = 0;

		this.ran = 0;
		this.order = -1;

		// array of current snapshots:
		this._snapshots = [];

		// setup the trial sequence:
		this._prepareSequence();

		this._experimentHandler = null;
		this.thisTrial = null;
		this._finished = false;
	}

	/**
	 * Helps go through each trial in the sequence one by one, mirrors PsychoPy.
	 */
	next()
	{
		const trialIterator = this[Symbol.iterator]();
		const { value } = trialIterator.next();

		return value;
	}

	/**
	 * Iterator over the trial sequence.
	 *
	 * &lt;p>This makes it possible to iterate over all trials.&lt;/p>
	 * @example
	 * let handler = new TrialHandler({nReps: 5});
	 * for (const thisTrial of handler) { console.log(thisTrial); }
	 */
	[Symbol.iterator]()
	{
		return {
			next: () =>
			{
				this.thisTrialN++;
				this.thisN++;
				this.nRemaining--;

				// check for the last trial:
				if (this.nRemaining === 0)
				{
					// this only indicated that the scheduling is done, not that the loop is finished
					// this.finished = true;
				}

				// start a new repetition:
				if (this.thisTrialN === this.nStim)
				{
					this.thisTrialN = 0;
					this.thisRepN++;
				}

				// check if we have completed the sequence:
				if (this.thisRepN >= this.nReps)
				{
					this.thisTrial = null;
					return { done: true };
				}

				this.thisIndex = this._trialSequence[this.thisRepN][this.thisTrialN];
				this.thisTrial = this.trialList[this.thisIndex];
				this.ran = 1;
				this.order = this.thisN;
				/*
				if self.autoLog:
					msg = 'New trial (rep=%i, index=%i): %s'
					vals = (self.thisRepN, self.thisTrialN, self.thisTrial)
					logging.exp(msg % vals, obj=self.thisTrial)*/

				return { value: this.thisTrial, done: false };
			},
		};
	}

	/**
	 * Execute the callback for each trial in the sequence.
	 *
	 * @param callback
	 */
	forEach(callback)
	{
		const trialIterator = this[Symbol.iterator]();

		while (true)
		{
			const result = trialIterator.next();
			if (result.done)
			{
				break;
			}

			callback(result.value);
		}
	}

	/**
	 * @typedef {Object} Snapshot
	 * @property {TrialHandler} handler - the trialHandler
	 * @property {string} name - the trialHandler name
	 * @property {number} nStim - the number of stimuli
	 * @property {number} nTotal - the total number of trials that will be run
	 * @property {number} nRemaining - the total number of trial remaining
	 * @property {number} thisRepN - the current repeat
	 * @property {number} thisTrialN - the current trial number within the current repeat
	 * @property {number} thisN - the total number of trials completed so far
	 * @property {number} thisIndex - the index of the current trial in the conditions list
	 * @property {number} ran - whether or not the trial ran
	 * @property {number} finished - whether or not the trials finished
	 * @property {Object} trialAttributes - a list of trial attributes
	 */
	/**
	 * Get a snapshot of the current internal state of the trial handler (e.g. current trial number,
	 * number of trial remaining).
	 *
	 * &lt;p>This is typically used in the LoopBegin function, in order to capture the current state of a TrialHandler&lt;/p>
	 *
	 * @return {Snapshot} - a snapshot of the current internal state.
	 */
	getSnapshot()
	{
		const currentIndex = this.thisIndex;

		const snapshot = {
			handler: this,
			name: this.name,
			nStim: this.nStim,
			nTotal: this.nTotal,
			nRemaining: this.nRemaining,
			thisRepN: this.thisRepN,
			thisTrialN: this.thisTrialN,
			thisN: this.thisN,
			thisIndex: this.thisIndex,
			ran: this.ran,
			finished: this._finished,

			getCurrentTrial: () => this.getTrial(currentIndex),
			getTrial: (index = 0) => this.getTrial(index),

			addData: (key, value) => this.addData(key, value),
		};

		// add to the snapshots the current trial's attributes:
		const currentTrial = this.getCurrentTrial();
		const excludedAttributes = ["handler", "name", "nStim", "nRemaining", "thisRepN", "thisTrialN", "thisN", "thisIndex", "ran", "finished"];
		const trialAttributes = [];
		for (const attribute in currentTrial)
		{
			if (!(attribute in excludedAttributes))
			{
				snapshot[attribute] = currentTrial[attribute];
				trialAttributes.push(attribute);
			}
			else
			{
				this._psychoJS.logger.warn(`attempt to replace the value of protected TrialHandler variable: ${attribute}`);
			}
		}
		snapshot.trialAttributes = trialAttributes;

		// add the snapshot to the list:
		this._snapshots.push(snapshot);

		return snapshot;
	}

	/**
	 * Setter for the seed attribute.
	 *
	 * @param {boolean} seed - the seed value
	 * @param {boolean} log - whether or not to log the change of seed
	 */
	setSeed(seed, log)
	{
		this._setAttribute("seed", seed, log);

		if (typeof seed !== "undefined")
		{
			this._randomNumberGenerator = seedrandom(seed);
		}
		else
		{
			this._randomNumberGenerator = seedrandom();
		}
	}

	/**
	 * Set the internal state of the snapshot's trial handler from the snapshot.
	 *
	 * @param {Snapshot} snapshot - the snapshot from which to update the current internal state of the
	 * 	snapshot's trial handler
	 */
	static fromSnapshot(snapshot)
	{
		// if snapshot is undefined, do nothing:
		if (typeof snapshot === "undefined")
		{
			return;
		}

		snapshot.handler.nStim = snapshot.nStim;
		snapshot.handler.nTotal = snapshot.nTotal;
		snapshot.handler.nRemaining = snapshot.nRemaining;
		snapshot.handler.thisRepN = snapshot.thisRepN;
		snapshot.handler.thisTrialN = snapshot.thisTrialN;
		snapshot.handler.thisN = snapshot.thisN;
		snapshot.handler.thisIndex = snapshot.thisIndex;
		snapshot.handler.ran = snapshot.ran;
		snapshot.handler._finished = snapshot._finished;
		snapshot.handler.thisTrial = snapshot.handler.getCurrentTrial();

		// add the snapshot's trial attributes to a global variable, whose name is derived from
		// that of the handler: loops -> thisLoop (note the dropped s):
		let name = snapshot.name;
		if (name[name.length - 1] === "s")
		{
			name = name.substr(0, name.length - 1);
		}
		name = `this${name[0].toUpperCase()}${name.substr(1)}`;

		const value = {};
		for (const attribute of snapshot.trialAttributes)
		{
			value[attribute] = snapshot[attribute];
		}
		window[name] = value;
	}

	/**
	 * Getter for the finished attribute.
	 *
	 * @returns {boolean} whether or not the trial has finished.
	 */
	get finished()
	{
		return this._finished;
	}

	/**
	 * Setter for the finished attribute.
	 *
	 * @param {boolean} isFinished - whether or not the loop is finished.
	 */
	set finished(isFinished)
	{
		this._finished = isFinished;

		this._snapshots.forEach((snapshot) =>
		{
			snapshot.finished = isFinished;
		});
	}

	/**
	 * Get the trial index.
	 *
	 * @return {number} the current trial index
	 */
	getTrialIndex()
	{
		return this.thisIndex;
	}

	/**
	 * Set the trial index.
	 *
	 * @param {number} index - the new trial index
	 */
	setTrialIndex(index)
	{
		this.thisIndex = index;
	}

	/**
	 * Get the attributes of the trials.
	 *
	 * &lt;p>Note: we assume that all trials in the trialList share the same attributes
	 * and consequently consider only the attributes of the first trial.&lt;/p>
	 *
	 * @return {Array.string} the attributes
	 */
	getAttributes()
	{
		if (!Array.isArray(this.trialList) || this.nStim === 0)
		{
			return [];
		}

		const firstTrial = this.trialList[0];
		if (!firstTrial)
		{
			return [];
		}

		return Object.keys(this.trialList[0]);
	}

	/**
	 * Get the current trial.
	 *
	 * @return {Object} the current trial
	 */
	getCurrentTrial()
	{
		return this.trialList[this.thisIndex];
	}

	/**
	 * Get the nth trial.
	 *
	 * @param {number} index - the trial index
	 * @return {Object|undefined} the requested trial or undefined if attempting to go beyond the last trial.
	 */
	getTrial(index = 0)
	{
		if (index &lt; 0 || index > this.nTotal)
		{
			return undefined;
		}

		return this.trialList[index];
	}

	/**
	 * Get the nth future or past trial, without advancing through the trial list.
	 *
	 * @param {number} [n = 1] - increment
	 * @return {Object|undefined} the future trial (if n is positive) or past trial (if n is negative)
	 * or undefined if attempting to go beyond the last trial.
	 */
	getFutureTrial(n = 1)
	{
		if (this.thisIndex + n &lt; 0 || n > this.nRemaining)
		{
			return undefined;
		}

		return this.trialList[this.thisIndex + n];
	}

	/**
	 * Get the nth previous trial.
	 * &lt;p> Note: this is useful for comparisons in n-back tasks.&lt;/p>
	 *
	 * @param {number} [n = -1] - increment
	 * @return {Object|undefined} the past trial or undefined if attempting to go prior to the first trial.
	 */
	getEarlierTrial(n = -1)
	{
		return getFutureTrial(-abs(n));
	}

	/**
	 * Add a key/value pair to data about the current trial held by the experiment handler
	 *
	 * @param {Object} key - the key
	 * @param {Object} value - the value
	 */
	addData(key, value)
	{
		if (this._experimentHandler)
		{
			this._experimentHandler.addData(key, value);
		}
	}

	/**
	 * Import a list of conditions from a .xls, .xlsx, .odp, or .csv resource.
	 *
	 * &lt;p>The output is suitable as an input to 'TrialHandler', 'trialTypes' or
	 * 'MultiStairHandler' as a 'conditions' list.&lt;/p>
	 *
	 * &lt;p>The resource should contain one row per type of trial needed and one column
	 * for each parameter that defines the trial type. The first row should give
	 * parameter names, which should:
	 * &lt;ul>
	 * &lt;li>be unique&lt;/li>
	 * &lt;li>begin with a letter (upper or lower case)&lt;/li>
	 * &lt;li>contain no spaces or other punctuation (underscores are permitted)&lt;/li>
	 * &lt;/ul>&lt;/p>
	 *
	 * &lt;p>Note that we only consider the first worksheet for .xls, .xlsx and .odp resource.&lt;/p>
	 *
	 *
	 * &lt;p> 'selection' is used to select a subset of condition indices to be used
	 * It can be a single integer, an array of indices, or a string to be parsed, e.g.:
	 *	5
	 *	[1,2,3,10]
	 *	'1,5,10'
	 *	'1:2:5'
	 *	'5:'
	 *	'-5:-2, 9, 11:5:22'
	 *
	 * @param {module:core.ServerManager} serverManager - the server manager
	 * @param {String} resourceName - the name of the resource containing the list of conditions, which must have been registered with the server manager.
	 * @param {Object} [selection = null] - the selection
	 * @return {Object} the parsed conditions as an array of 'object as map'
	 * @throws {Object} Throws an exception if importing the conditions failed.
	 */
	static importConditions(serverManager, resourceName, selection = null)
	{
		try
		{
			const resourceExtension = resourceName.split(".").pop();
			if (["csv", "odp", "xls", "xlsx"].indexOf(resourceExtension) > -1)
			{
				// (*) read conditions from resource:
				const resourceValue = serverManager.getResource(resourceName, true);

				// Conditionally use a `TextDecoder` to reprocess .csv type input,
				// which is then read in as a string
				const decodedResourceMaybe = new Uint8Array(resourceValue);
				// Could be set to 'buffer' for ASCII .csv
				const type = resourceExtension === "csv" ? "string" : "array";
				const decodedResource = type === "string" ? (new TextDecoder()).decode(decodedResourceMaybe) : decodedResourceMaybe;
				const workbook = XLSX.read(decodedResource, { type });

				// we consider only the first worksheet:
				if (workbook.SheetNames.length === 0)
				{
					throw "workbook should contain at least one worksheet";
				}
				const sheetName = workbook.SheetNames[0];
				const worksheet = workbook.Sheets[sheetName];

				// worksheet to array of arrays (the first array contains the fields):
				const sheet = XLSX.utils.sheet_to_json(worksheet, { header: 1, blankrows: false });
				const fields = sheet.shift();

				// (*) select conditions:
				const selectedRows = (selection === null) ? sheet : util.selectFromArray(sheet, selection);

				// (*) return the selected conditions as an array of 'object as map':
				// [
				// {field0: value0-0, field1: value0-1, ...}
				// {field0: value1-0, field1: value1-1, ...}
				// ...
				// ]
				let trialList = new Array(selectedRows.length - 1);
				for (let r = 0; r &lt; selectedRows.length; ++r)
				{
					let row = selectedRows[r];
					let trial = {};
					for (let l = 0; l &lt; fields.length; ++l)
					{
						let value = row[l];

						// Look for string encoded arrays in the form of '[1, 2]'
						const arrayMaybe = util.turnSquareBracketsIntoArrays(value);

						if (Array.isArray(arrayMaybe))
						{
							// Keep the first match if more than one are found. If the
							// input string looked like '[1, 2][3, 4]' for example,
							// the resulting `value` would be [1, 2]. When `arrayMaybe` is
							// empty, `value` turns `undefined`.
							value = arrayMaybe;
						}

						if (typeof value === "string")
						{
							const numberMaybe = Number.parseFloat(value);

							// if value is a numerical string, convert it to a number:
							if (!isNaN(numberMaybe) &amp;&amp; numberMaybe.toString().length === value.length)
							{
								value = numberMaybe;
							}
							else
							{
								// Parse doubly escaped line feeds
								value = value.replace(/(\n)/g, "\n");
							}
						}

						trial[fields[l]] = value;
					}
					trialList[r] = trial;
				}

				return trialList;
			}
			else
			{
				throw "extension: " + resourceExtension + " currently not supported.";
			}
		}
		catch (error)
		{
			throw {
				origin: "TrialHandler.importConditions",
				context: `when importing condition: ${resourceName}`,
				error,
			};
		}
	}

	/**
	 * Prepare the trial list.
	 *
	 * @protected
	 * @returns {void}
	 */
	_prepareTrialList()
	{
		const response = {
			origin: "TrialHandler._prepareTrialList",
			context: "when preparing the trial list",
		};

		// we treat undefined trialList as a list with a single empty entry:
		if (typeof this._trialList === "undefined")
		{
			this.trialList = [undefined];
		}
		// if trialList is an array, we make sure it is not empty:
		else if (Array.isArray(this._trialList))
		{
			if (this._trialList.length === 0)
			{
				this.trialList = [undefined];
			}
		}
		// if trialList is a string, we treat it as the name of the condition resource:
		else if (typeof this._trialList === "string")
		{
			this.trialList = TrialHandler.importConditions(this.psychoJS.serverManager, this._trialList);
		}
		// unknown type:
		else
		{
			throw Object.assign(response, {
				error: `unable to prepare trial list: unknown type: ${(typeof this._trialList)}`
			});
		}
	}

	/**
	 * Prepare the sequence of trials.
	 *
	 * &lt;p>The returned sequence is a matrix (an array of arrays) of trial indices
	 * with nStim columns and nReps rows. Note that this is the transpose of the
	 * matrix return by PsychoPY.
	 *
	 * Example: with 3 trial and 5 repetitions, we get:
	 *   - sequential:
	 *      [[0 1 2]
	 *       [0 1 2]
	 *       [0 1 2]
	 *       [0 1 2]
	 *       [0 1 2]]
	 *
	 * These 3*5 = 15 trials will be returned by the TrialHandler generator
	 * - with method = 'sequential' in the order:
	 *    0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2
	 * - with method = 'random' in the order (amongst others):
	 *    2, 1, 0, 0, 2, 1, 0, 1, 2, 0, 1, 2, 1, 2, 0
	 * - with method = 'fullRandom' in the order (amongst others):
	 *    2, 0, 0, 1, 0, 2, 1, 2, 0, 1, 1, 1, 2, 0, 2
	 * &lt;/p>
	 *
	 * @protected
	 **/
	_prepareSequence()
	{
		const response = {
			origin: "TrialHandler._prepareSequence",
			context: "when preparing a sequence of trials",
		};

		// get an array of the indices of the elements of trialList:
		const indices = Array.from(this.trialList.keys());

		if (this._method === TrialHandler.Method.SEQUENTIAL)
		{
			this._trialSequence = Array(this.nReps).fill(indices);
			// transposed version:
			// this._trialSequence = indices.reduce( (seq, e) => { seq.push( Array(this.nReps).fill(e) ); return seq; }, [] );
		}
		else if (this._method === TrialHandler.Method.RANDOM)
		{
			this._trialSequence = [];
			for (let i = 0; i &lt; this.nReps; ++i)
			{
				this._trialSequence.push(util.shuffle(indices.slice(), this._randomNumberGenerator));
			}
		}
		else if (this._method === TrialHandler.Method.FULL_RANDOM)
		{
			// create a flat sequence with nReps repeats of indices:
			const flatSequence = [];
			for (let i = 0; i &lt; this.nReps; ++i)
			{
				flatSequence.push.apply(flatSequence, indices);
			}

			// shuffle the sequence:
			util.shuffle(flatSequence, this._randomNumberGenerator);

			// reshape it into the trialSequence:
			this._trialSequence = [];
			for (let i = 0; i &lt; this.nReps; i++)
			{
				this._trialSequence.push(flatSequence.slice(i * this.nStim, (i + 1) * this.nStim));
			}
		}
		else
		{
			throw Object.assign(response, { error: "unknown method" });
		}

		return this._trialSequence;
	}
}

/**
 * TrialHandler method
 *
 * @enum {Symbol}
 * @readonly
 */
TrialHandler.Method = {
	/**
	 * Conditions are presented in the order they are given.
	 */
	SEQUENTIAL: Symbol.for("SEQUENTIAL"),

	/**
	 * Conditions are shuffled within each repeat.
	 */
	RANDOM: Symbol.for("RANDOM"),

	/**
	 * Conditions are fully randomised across all repeats.
	 */
	FULL_RANDOM: Symbol.for("FULL_RANDOM"),

	/**
	 * Same as above, but named to reflect PsychoPy boileplate.
	 */
	FULLRANDOM: Symbol.for("FULL_RANDOM"),
};
</code></pre>
        </article>
    </section>




    
    
</div>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.7</a> on Mon Aug 01 2022 10:19:55 GMT+0200 (Central European Summer Time) using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
</footer>

<script>prettyPrint();</script>
<script src="scripts/polyfill.js"></script>
<script src="scripts/linenumber.js"></script>

<script src="scripts/search.js" defer></script>



</body>
</html>
